import {baseURL} from "@/env"
import { login } from "./util";
var app = getApp();
enum Method {
    GET = "GET",
    POST = "POST",
    PUT = "PUT",
    DELETE = "DELETE",
}
/**
 * @name: 用户请求方法，使用promise实现
 * @author: camellia
 * @date: 2021-11-08
 * @param {*} method 请求方式
 * @param {*} url 请求连接
 * @param {*} data 请求数据
 * @param {*} header 请求头
 */
export function request(method: 'GET' | 'POST' | 'PUT' | 'DELETE', url: string, data?: any, header?: Record<string, string>) {
    return new Promise(function (resolve, reject) {
        let header_inner = {
            "content-type": "application/json",
            "Authorization": `Bearer ${wx.getStorageSync('token')}`,
            ...header
        };
        var requestData = data;
        if (method == "POST") {
            requestData = JSON.stringify(data);
        }
        wx.showLoading({
            title: '加载中...',
        })
        wx.request({
            url: baseURL + url,
            method: method,
            data: requestData,
            header: header_inner,
            async success(result: any) {
                // 判断错误状态码
                if (result.data.statusCode) {
                    const statusCode = result.data.statusCode
                    if (statusCode === 401) {
                        // wx.showToast({
                        //     title: '自动登录成功',
                        //     icon: 'none'
                        // })
                        await login()
                    }
                    if (statusCode === 404) {
                        wx.showToast({
                            icon: 'error',
                            title: result.data.error,
                        })
                    }
                }
                if (result.data.code) {
                    resolve(result);
                } else {
                    wx.hideLoading()
                    // 其他异常
                    resolve(result);
                }
            },
            fail(e) {
                console.error(`请求发送错误`, e);
                //请求发送失败
                wx.showToast({
                    title: '请检查本地网络',
                    duration: 1000
                })
                resolve(data);
            },
            complete: (e) => {
                wx.hideLoading()
                resolve(e)
            },
        });
    });
};

